<script setup lang="ts">
import {MenuOption} from "naive-ui"
import {onBeforeMount, ref, watch} from "vue"
import {useRouter, useRoute} from "vue-router"
import {Logo} from '@components'
import {MenuObjPropNameEnum} from '../enums/menu-obj-prop-name-enum.ts'
import {MenuTypeEnum} from '../enums/menu-type-enum.ts'
import {useMenuStore} from '../stores/menu-store.ts'

const router = useRouter()
const route = useRoute()

/**
 * 组件参数
 */
const {
  collapsed = false,
  collapsedWidth = 64
} = defineProps<{
  // 菜单是否收缩
  collapsed: boolean
  // 折叠后菜单的宽度
  collapsedWidth: number
}>()

// 获取菜单信息数据
onBeforeMount(async () => {
  if (useMenuStore().getMenuOptions().length > 0) return
  await useMenuStore().getMenuDataByReq()
})

// 激活菜单项时的处理函数
const activeMenuHandler = (key: number, option: MenuOption) => {
  // 如果当前路由路径与激活菜单项的路由路径相同，则不做任何操作，防止路由跳转
  if (route.path === option[MenuObjPropNameEnum.ROUTE_PATH]) return
  // 如果激活的菜单项的类型为外链，则直接新建标签页打开外链，不修改选中菜单项的值
  if (option[MenuObjPropNameEnum.TYPE] === MenuTypeEnum.LINK) {
    window.open(option[MenuObjPropNameEnum.LINK_PATH] as string, '_blank')
    return
  }
  // 保存激活菜单项的 key
  useMenuStore().setActiveMenu(key)
  // 路由跳转
  router.push({
    path: option[MenuObjPropNameEnum.ROUTE_PATH] as string,
    query: option[MenuObjPropNameEnum.ROUTE_QUERY] as Record<string, string>
  })
}

/**
 * 响应式处理
 */
// 菜单是否折叠收缩
const isCollapsed = ref(collapsed)
// 监听组件参数 collapsed 的变化
watch(
  () => collapsed,
  (newVal) => isCollapsed.value = newVal
)
</script>

<template>
  <div class="menu relative h-screen box-bg">
    <div class="logo">
      <Logo :is-collapsed="collapsed" />
    </div>
    <n-menu
      :value="useMenuStore().getMenuKeySelected()"
      @update:value="activeMenuHandler"
      v-model:collapsed="isCollapsed"
      :collapsed-width="collapsedWidth"
      :options="useMenuStore().getMenuOptions()"
      :indent="24"
      :root-indent="18"
    />
  </div>
</template>

<style scoped>

</style>
